<script setup lang="ts">
import { computed, type PropType } from "vue";
import { omitNil } from "@/framework/util/objects";

defineOptions({ name: "grid" });
const props = defineProps({
  inline: { type: Boolean },
  rowsPreset: { type: String as PropType<keyof typeof rowPresets> },
  rowTemplate: { type: String },
  colsPreset: { type: String as PropType<keyof typeof colPresets> },
  colTemplate: { type: String },
  gap: { type: [String, Number] as PropType<string | number> },
  rowGap: { type: [String, Number] as PropType<string | number> },
  colGap: { type: [String, Number] as PropType<string | number> },
});

const rowPresets = {
  "two-rows-0": "min-content minmax(0, 1fr)",
  "two-rows-1": "minmax(0, 1fr) min-content",
};

const colPresets = {
  "two-cols-0": "min-content minmax(0, 1fr)",
  "two-cols-1": "minmax(0, 1fr) min-content",
};

const style = computed(() => {
  return omitNil({
    display: props.inline ? "inline-grid" : undefined,
    gridTemplateRows: props.rowTemplate || (props.rowsPreset && rowPresets[props.rowsPreset]),
    gridTemplateColumns: props.colTemplate || (props.colsPreset && colPresets[props.colsPreset]),
    gap: typeof props.gap === "number" ? props.gap + "px" : props.gap,
    rowGap: typeof props.rowGap === "number" ? props.rowGap + "px" : props.rowGap,
    columnGap: typeof props.colGap === "number" ? props.colGap + "px" : props.colGap,
  });
});
</script>

<template>
  <div :class="['grid', rowsPreset, colsPreset]" :style="style">
    <slot />
  </div>
</template>

<style lang="less">
.grid {
  display: grid;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  overflow: hidden;

  > * {
    box-sizing: border-box;
  }

  &.two-rows-0 > *:last-child {
    overflow: auto;
  }

  &.two-rows-1 > *:first-child {
    overflow: auto;
  }

  &.two-cols-0 > *:last-child {
    overflow: auto;
  }

  &.two-cols-1 > *:first-child {
    overflow: auto;
  }
}
</style>
